package com.agent.vpsserver.common.utils;

import com.agent.vpsserver.common.exception.BusinessException;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
public class RemoteCommandUtil {

    public static Session createSession(String hostname, String username, String password) {
        return RemoteCommandUtil.createSession(hostname, 22, username, password);
    }

    public static Session createSession(String hostname, int port, String username, String password) {
        JSch jsch = new JSch();

        try {
            // 创建 SSH 会话
            Session session = jsch.getSession(username, hostname, port);
            session.setPassword(password);

            // 忽略主机密钥检查
            session.setConfig("StrictHostKeyChecking", "no");

            // 连接 SSH 会话
            session.connect();
            return session;
        } catch (JSchException e) {
            throw new BusinessException("建立ssh失败", e);
        }
    }

    public static String exec(String command, Session session) {
        // 打开 SSH 通道
        Channel channel = null;
        try {
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            // 获取命令执行结果
            InputStream inputStream = channel.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            // 连接 SSH 通道
            channel.connect();

            // 读取命令执行结果
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            return output.toString();
        } catch (JSchException e) {
            throw new BusinessException("执行远程命令失败", e);
        } catch (IOException e) {
            throw new BusinessException("获取远程命令结果失败", e);
        } finally {
            if (channel != null) {
                // 关闭 SSH 通道和会话
                channel.disconnect();
            }
        }
    }

    public static String exec(String hostname, String username, String password, String command) {
        return RemoteCommandUtil.exec(hostname, 22, username, password, command);
    }

    public static String exec(String hostname, int port, String username, String password, String command) {
        Session session = RemoteCommandUtil.createSession(hostname, port, username, password);
        try {
            return RemoteCommandUtil.exec(command, session);
        } finally {
            session.disconnect();
        }
    }
}